import { createRouter, createWebHistory } from 'vue-router'

import UserListView from '@/views/user/ListView.vue'
import UserSaveView from '@/views/user/SaveView.vue'

import FoodListView from '@/views/food/ListView.vue'
import FoodSaveView from '@/views/food/SaveView.vue'

import CategoryListView from '@/views/category/ListView.vue'
import FlavorListView from '@/views/flavor/ListView.vue'

import BookListView from '@/views/book/ListView.vue'
import BookDetailView from '@/views/book/DetailView.vue'

const routes = [
  {
    path: '/',
    component: () => import('../views/layout/LayoutView.vue'),
    children: [
      {
        path: '/',
        redirect: '/user/list'
      },
      {
        path: '/user/list',
        name: 'userListView',
        component: UserListView
      },
      {
        path: '/user/save',
        name: 'userSaveView',
        component: UserSaveView
      },
      {
        path: '/category/list',
        name: 'categoryListView',
        component: CategoryListView
      },
      {
        path: '/flavor/list',
        name: 'flavorListView',
        component: FlavorListView
      },
      {
        path: '/food/list',
        name: 'foodListView',
        component: FoodListView
      },
      {
        path: '/food/save',
        name: 'foodSaveView',
        component: FoodSaveView
      },
      {
        path: '/book/list',
        name: 'bookListView',
        component: BookListView
      },
      {
        path: '/book/:num',
        name: 'bookDetailView',
        component: BookDetailView
      }
    ]
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue')
  }
]

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes
})

router.beforeEach((to, from, next) => {
  const token = sessionStorage.getItem('token')
  const toPath = to.path
  if (toPath == '/login') {
    //判断是否已经登录过了
    if (token) {
      next({ path: '/user/list' })
    } else {
      next()
    }
  } else {
    //判断是否已经登录
    if (token) {
      //已经登录了
      next()
    } else {
      next({ path: '/login' })
    }
  }
})

export default router
